package com.java.cart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java.cart.mapper.CartMapper;
import com.java.cart.service.CartService;
import com.java.clients.ProductClient;
import com.java.param.CartListParam;
import com.java.param.ProductCollectParam;
import com.java.param.ProductIdParam;
import com.java.param.ProductIdRemoveParam;
import com.java.pojo.Cart;
import com.java.pojo.Product;
import com.java.utils.R;
import com.java.vo.CartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductClient productClient;
    /**
     * 通过用户id和商品id将商品详细信息保存到购物车中
     *
     * @param cart
     * @return 商品详细信息CartVo
     */
    @Override
    public R save(Cart cart) {

        //调用商品服务，获取商品信息
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cart.getProductId());
        Product product = productClient.detail(productIdParam);
        //查询是否有库存
        if(product==null){
            return R.fail("商品已经被删除，无法添加到购物车！");
        }
        if(product.getProductNum()<1){
            R ok = R.ok("没有库存，无法购买！");
            ok.setCode("003");
            log.info("CartServiceImpl.save 业务已经完成,结果:{}", ok);
            return ok;
        }
        //判断商品是否是第一次加入购物车
        //是，返回数量为1
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId());
        queryWrapper.eq("product_id",cart.getProductId());
        Cart cartOne = cartMapper.selectOne(queryWrapper);
        if(cartOne!=null){
            //存在商品，
            cartOne.setNum(cartOne.getNum()+1);
            cartMapper.update(cartOne,queryWrapper);
            R ok = R.ok("该商品已在购物车，数量 +1");
            ok.setCode("002");
            log.info("CartServiceImpl.save 业务已经完成,结果:{}", ok);
            return ok;
        }
        //商品第一次加入购物车
        cart.setNum(1);
        int rows = cartMapper.insert(cart);
        CartVo cartVo = new CartVo(product,cart);
        log.info("CartServiceImpl.save 业务已经完成,结果:{}", cartVo);
        return R.ok("添加购物车成功！", cartVo);

    }

    /**
     * 通过用户id查询所有商品id集合，再根据商品id查询所有商品信息
     *
     * @param cartListParam
     * @return CartVo类型
     */
    @Override
    public R list(CartListParam cartListParam) {

        //封装参数
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cartListParam.getUserId());
        List<Cart> carts = cartMapper.selectList(queryWrapper);
        //判断购物车
        if(carts==null||carts.size()==0){
            return R.ok("购物车没有数据！",carts);
        }

        //获取商品ids
        List<Integer> productIds = new ArrayList<>();
        for (Cart cart : carts) {
            productIds.add(cart.getProductId());
        }

        //获取商品信息
        ProductCollectParam productCollectParam = new ProductCollectParam();
        productCollectParam.setProductIds(productIds);
        List<Product> products = productClient.cartList(productCollectParam);

        //商品集合转换成商品map,商品id - key ,商品 - value
        //jdk8 stream流转换成map
        Map<Integer, Product> productMap = products.stream().collect(Collectors.toMap(Product::getProductId, v -> v));

        List<CartVo> cartVoList = new ArrayList<>();
        for (Cart cart : carts) {
            cartVoList.add(new CartVo(productMap.get(cart.getProductId()),cart));
        }

        R ok = R.ok("购物车数据查询成功！", cartVoList);

        log.info("CartServiceImpl.list 业务已经完成,结果:{}",ok);
        return ok;
    }

    /**
     * 根据商品id查询商品信息
     * 修改购物车数量
     *
     * @param cart
     * @return
     */
    @Override
    public R update(Cart cart) {
        //根据商品id查询商品信息
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cart.getProductId());
        Product product = productClient.detail(productIdParam);

        if(product==null){
            log.info("CartServiceImpl.update 业务已经完成,结果:{}", "修改失败，商品已被删除！");
            return R.fail("修改失败，商品已被删除！");
        }
        if(cart.getNum()>product.getProductNum()){
            log.info("CartServiceImpl.update 业务已经完成,结果:{}", "修改失败，超过库存容量！");
            return R.fail("修改失败，超过库存容量！");
        }
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId());
        queryWrapper.eq("product_id",cart.getProductId());
        int rows = cartMapper.update(cart, queryWrapper);
        if(rows==0){
            return R.fail("购物车数量更新失败！");
        }
        log.info("CartServiceImpl.update 业务已经完成,结果:{}", cart);
        return R.ok("购物车数量更新成功！");
    }

    /**
     * 根据用户id和商品id删除购物车内的数据
     *
     * @param cart
     * @return
     */
    @Override
    public R remove(Cart cart) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId());
        queryWrapper.eq("product_id",cart.getProductId());
        int rows = cartMapper.delete(queryWrapper);
        if(rows==0){
            log.info("CartServiceImpl.remove 业务已经完成,结果:{}", "商品删除失败！");
            return R.fail("删除购物车失败！");
        }
        log.info("CartServiceImpl.remove 业务已经完成,结果:{}", "删除购物车成功！");
        return R.ok("删除购物车成功！");
    }

    /**
     * 清空对应id的购物车项
     *
     * @param cartIds
     */
    @Override
    public void clearIds(List<Integer> cartIds) {
        cartMapper.deleteBatchIds(cartIds);
        log.info("CartServiceImpl.clearIds 业务已经完成,结果:{}", cartIds);
    }

    /**
     * 根据商品id检查所有用户购物车是否有该商品
     *
     * @param productIdRemoveParam
     * @return
     */
    @Override
    public R check(ProductIdRemoveParam productIdRemoveParam) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id",productIdRemoveParam.getProductId());
        Cart cart = cartMapper.selectOne(queryWrapper);
        if(cart!=null){
            return R.fail("存在用户购物车含有该商品，不可删除！");
        }
        return R.ok("不存在用户购物车含有该商品，可以删除！");
    }
}
